package feiyanren.com;

public class A04_Demo4 {
    public static void main(String[] args) {
        int[] arr = {4, 3, 5, 6, 7};
        quickSort(arr, 0, arr.length - 1);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }

    public static void quickSort(int[] arr, int i, int j) {
        int start = i;
        int end = j;
        if (start > end) {
            return;
        }
        //基准数为第一个起始值
        int baseNumber = arr[i];
        while (start != end) {
            //先动end，再动start(为了让end先找到比基准数小的数，后来与基准数换位的时候，基准数左边的数都比基准数小)
            while (true) {
                if (start >= end || arr[end] < baseNumber) {
                    break;
                }
                end--;
            }
            while (true) {
                if (start >= end || arr[start] > baseNumber) {
                    break;
                }
                start++;
            }
            //交换start和end的位置
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
        }
        //基准数和end&start相遇的位置交换
        int temp = arr[i];
        arr[i] = arr[start];
        arr[start] = temp;
        //递归调用左半数组
        quickSort(arr, i, start - 1);
        //递归调用右半数组
        quickSort(arr, start + 1, j);
    }

}
